<?php
include 'db.class.php';
class cmysql extends cdb{
	
	function cmysql($dbhost, $user, $pwd, $dbname, $charset='utf8') {
		if(function_exists('mysql_pconnect')) {
			if(!$connect = @mysql_pconnect($dbhost, $user, $pwd)) {
				exit("connection error.");
			}
		} else {
			if(!$connect = @mysql_connect($dbhost, $user, $pwd)) {
				exit("connection error.");
			}
		}
		$this->connect = $connect;
		$this->charset = $charset;
		$this->version = mysql_get_server_info($this->connect);
		$this->dbname = $dbname;
		if($this->version > '4.1') mysql_query("SET NAMES '$charset'", $connect);
		if($this->version > '5.0') mysql_query("SET sql_mode=''", $connect);
		if($dbname) mysql_select_db($dbname, $connect);
	}
	
	function insert($table, $values) {
		if(empty($values)) return;
		
		$sql = "INSERT INTO t_{$table} ";
		$keysql = '';
		$valuesql = '';
		foreach($values as $key => $value) {
			$keysql .= "c_$key,";
			$value = $this->addslashes($value);
			if(null==$value || ''==$value){
				$valuesql .= "null,";
			}
			else{ 
				$valuesql .= "'$value',";
			}
		}
		$keysql .= "c_created, c_creator, c_updated, c_updator";
		$cur = time();
		$valuesql .= "$cur, '$_SESSION[login]', $cur, '$_SESSION[login]'";
		$sql .= "($keysql)VALUES($valuesql)";
		if(mysql_query($sql)){
			return mysql_insert_id();
		}
	}
	function _commit() {}
	function _fetch_array($query) {
		return mysql_fetch_array($query, MYSQL_ASSOC);
	}
	function _query($sql) {
		return mysql_query($sql, $this->connect);
	}
	function _close() {
		mysql_close($this->connect);
	}
	function _error() {
		return mysql_error($this->connect);
	}
	
	/**
	 * 对$value进行mysql的escape
	 * @param $value
	 */
	function addslashes($value) {
		if(is_array($value)) {
			foreach($value as $k => $v) {
				$value[$k] = addslashes($v);
			}
		} else {
			if(function_exists('mysql_real_escape_string')) {
				$value = mysql_real_escape_string($value);
			} else {
				$value = addslashes($value);
			}
		}
		return $value;
	}
	
	/**
	 * 获取之前插入的记录的自动ID值
	 */
	function previnsertid() {
		return mysql_insert_id($this->connect);
	}
}
?>